package com.jstyle.beatecg.util;


import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;


import com.jstyle.beatecg.NetWork.NetWorkUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class ImageUtils {
	
	public static final int GET_IMAGE_BY_CAMERA = 5001;
	public static final int GET_IMAGE_FROM_PHONE = 5002;
	public static final int CROP_IMAGE = 5003;


	public static void openCameraImage(final Activity activity, Uri uri) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		activity.startActivityForResult(intent, ImageUtils.GET_IMAGE_BY_CAMERA);
	}
	
	public static void openLocalImage(final Activity activity) {
		Intent intent = new Intent(Intent.ACTION_PICK, null);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				"image/*");
		activity.startActivityForResult(intent, ImageUtils.GET_IMAGE_FROM_PHONE);
	}
	public static final String CHARSET = "UTF-8";
	public static String md5Encoder(String input) {
		String result = input;
		if (input != null) {
			MessageDigest md = null;
			try {
				md = MessageDigest.getInstance("MD5");
				md.update(input.getBytes(Charset.forName(CHARSET)));
				result = bytesToHexString(md.digest(), "");
				// result = getString(md.digest());
				return result;
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	public static String bytesToHexString(byte[] bytes, String separator) {
		StringBuilder hexString = new StringBuilder();
		for (byte b : bytes) {
			String hex = Integer.toHexString(0xFF & b);
			if (hex.length() == 1) {
				hexString.append('0');
			}
			hexString.append(hex).append(separator);
		}
		return hexString.toString();
	}
	public static void cropImage(Activity activity, int width, int height, Uri srcUri, Uri targetUri ) {
		
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(srcUri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", width);
		intent.putExtra("outputY", height);
		intent.putExtra("scale", true);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, targetUri);
		// return-data为true时,会直接返回bitmap数据,但是大图裁剪时会出现问题,推荐下面为false时的方式
		// return-data为false时,不会返回bitmap,但需要指定一个MediaStore.EXTRA_OUTPUT保存图片uri
		intent.putExtra("return-data", false);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		intent.putExtra("noFaceDetection", true); // no face detection
		
		////////////////////////////////////////////////////////////////
		// 1.宽高和比例都不设置时,裁剪框可以自行调整(比例和大小都可以随意调整)
		////////////////////////////////////////////////////////////////
		// 2.只设置裁剪框宽高比(aspect)后,裁剪框比例固定不可调整,只能调整大小
		////////////////////////////////////////////////////////////////
		// 3.裁剪后生成图片宽高(output)的设置和裁剪框无关,只决定最终生成图片大小
		////////////////////////////////////////////////////////////////
		// 4.裁剪框宽高比例(aspect)可以和裁剪后生成图片比例(output)不同,此时,
		//	会以裁剪框的宽为准,按照裁剪宽高比例生成一个图片,该图和框选部分可能不同,
		//  不同的情况可能是截取框选的一部分,也可能超出框选部分,向下延伸补足
		////////////////////////////////////////////////////////////////
		activity.startActivityForResult(intent, CROP_IMAGE);
	}
	public static boolean existSDCard() {
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		} else
			return false;
	}
	/**
	 * 创建一条图片地址uri,用于保存拍照后的照片
	 * @param context
	 * @return 图片的uri
	 */
	public static Uri createImagePathUri(Context context) {
		Uri imageFilePath = null;
//		String status = Environment.getExternalStorageState();
//		SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
		long time = System.currentTimeMillis();
		String imageName = "head";
		// ContentValues是我们希望这条记录被创建时包含的数据信息
		ContentValues values = new ContentValues(3);
		values.put(MediaStore.Images.Media.DISPLAY_NAME, imageName);
//		values.put(MediaStore.Images.Media.DATE_TAKEN, time);
		values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
		if (existSDCard()) {// 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
			imageFilePath = context.getContentResolver().insert(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
		} else {
			imageFilePath = context.getContentResolver().insert(
					MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
		}
		Log.i("", "生成的照片输出路径：" + imageFilePath.toString());
		return imageFilePath;
	}
	public static Bitmap decodeUriAsBitmap(Uri uri, Context context) {
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeStream(context.getContentResolver()
					.openInputStream(uri));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
		return bitmap;
	}
	
    
    
    
	private final static String baseDir = Environment.getExternalStorageDirectory()
			.getAbsolutePath() + "/" +"com.jstyle.beatecg";
	public final static String musicPath = baseDir + "/musics/";
	public final static String headPath = baseDir + "/images/";
	public final static String UPDATEPATH=baseDir+"/update/";
	public final static String shootPath=baseDir+"/shot/";
	public final static String ecgPath=baseDir+"/ecg/";
	public final static String pdfPath = baseDir + "/pdf/";
	public static String NODRIC="";
	public static String tempFilePath= headPath + ImageUtils.md5Encoder("tempFile");
	public static String socliaFilePath= headPath + ImageUtils.md5Encoder("socliaFile");
	public static String shotFilePath= shootPath + ImageUtils.md5Encoder("shot")+".jpg";
	private static File tempFile;
	private static final String TAG = "ImageUtils";
	private static String loginType="login_type";
	private static String spName = "jstyle_userinfo";
	public static Uri tempUri;
	public static Bitmap findHeadBitmap(Context context) {
		if (ImageUtils.existSDCard()) {
			// 不存在则创建目录
			File dir = new File(headPath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			String account= NetWorkUtil.getToken();
			Log.i(TAG, "findHeadBitmap: "+ImageUtils.md5Encoder(account));
			String tempFilePath=headPath+ImageUtils.md5Encoder(account);
			tempFile = new File(tempFilePath);
			if (!tempFile.exists()) {
				// 创建临时文件
				try {
					tempFile.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		tempUri = Uri.fromFile(tempFile);
		Bitmap bm = decodeUriAsBitmap(tempUri, context);
		return bm;
	};
	public static Bitmap decodeStringAsBitmap(String path){
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeFile(path);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return bitmap;
	}


	public static void setMargins (View v, int l, int t, int r, int b) {
		if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
			ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
			p.setMargins(l, t, r, b);
			v.requestLayout();
		}
	}

}
